package cn.it.shop.service.listener;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.it.shop.service.CategoryService;
import cn.it.shop.service.PrivilegeService;
import cn.it.shop.util.ShopTimerTask;
/*
 * 在Spring中,ContextLoaderListener此监听器加载的Spring的配置文件,并且把它存储到application内置对象中
 * 那么我们可以通过app key获取此文件,以后在其他的监听、拦截器、过滤器都可能需要用到此文件
 * */
public class InitShopDataListener implements ServletContextListener {
	
	private CategoryService categoryService=null;
	
	private PrivilegeService privilegeService=null;
	
	private ApplicationContext context=null;


	@Override
	public void contextInitialized(ServletContextEvent event) {
		System.out.println("----contextInitialized----");
//		context=(ApplicationContext)event.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		// 可以从application内置对象中获取Spring配置文件
		context=WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
		// 获取categoryService,调用query方法,查询所有类别, 并且存储到application中
		categoryService=(CategoryService)context.getBean("categoryService");
		// 获取权限的Service查询所有权限信息(支持层次结构 /级联)
		privilegeService=(PrivilegeService)context.getBean("privilegeService");
		// 把所有类别查询存储到application内置对象(并没有关联Account)
		event.getServletContext().setAttribute("categoryList",categoryService.query());
		
		// 定时器,每隔一段时间同步首页的商品信息,首先从Spring获取ShopTimerTask
		ShopTimerTask shopTimerTask=(ShopTimerTask)context.getBean("shopTimerTask");
		// 通过set方法传入application内置对象
		shopTimerTask.setApplication(event.getServletContext());
		// 设置线程的运行起始时间,和运行周期  0 立即执行一次    1000*10 每隔10秒在执行
		new Timer(true).schedule(shopTimerTask, 0, 1000*60*60*24);
		
		// 获取银行图标,并且存储都application中
		String basePath=event.getServletContext().getRealPath("/");
		System.out.println("basePath=" + basePath);
		File file = new File(basePath + "image/bank/");
		String[] bankList=file.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".gif");
			}
		});
		event.getServletContext().setAttribute("bankList", bankList);
		// 查询所有的权限(URL), 支持树状显示
		event.getServletContext().setAttribute("privilegeList", privilegeService.queryForTree());
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		
	}

}
